package com.nopay.cdxphone.ui.ativity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.inputmethod.EditorInfo;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nopay.cdxphone.Constants;
import com.nopay.cdxphone.R;
import com.nopay.cdxphone.base.BaseActivity;
import com.nopay.cdxphone.bean.request.LoginRequest;
import com.nopay.cdxphone.bean.response.LoginResponse;
import com.nopay.cdxphone.databinding.ActivityLoginBinding;
import com.nopay.cdxphone.utils.DeviceIdManager;
import com.nopay.cdxphone.utils.RememberUitls;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @ProjectName: myVisualPhone
 * @Package: cn.cn.myvisualphone.ui.ativity
 * @ClassName: LoginActivity
 * @Description: java类作用描述
 * @Author: anqi
 * @CreateDate: 2021/5/23 8:04
 * @UpdateUser: 更新者
 * @UpdateDate: 2021/5/23 8:04
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class LoginActivity extends BaseActivity<ActivityLoginBinding> {

    @Override
    protected void init(Bundle savedInstanceState, Object... preData) {
        binding.rlRoot.setPadding(0, getStatusBarHeight(com.nopay.cdxphone.ui.ativity.LoginActivity.this), 0, 0);
        binding.commitBtn.setOnClickListener(v -> {
            if(checkInput()) getPermissionToLogin();
        });

        binding.tvToRisigter.setOnClickListener(v -> mSwipeBackHelper.forward(RegisterActivity.class));

        binding.tvFindPwd.setOnClickListener(v -> mSwipeBackHelper.forward(ForgetActivity.class));

        // 密码输入完成，软键盘确认
        binding.loginEtPassword.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                if(checkInput()) getPermissionToLogin();
                return true;
            }
            return false;
        });

        boolean isRemember = SPUtils.getInstance().getBoolean(Constants.SP_IS_REMEMBER, true);
        binding.cbVerificationCodeLogin.setChecked(isRemember);
        // 是否记住密码
        binding.cbVerificationCodeLogin.setOnCheckedChangeListener((compoundButton, checked) -> {
            // TODO 记住密码
            SPUtils.getInstance().put(Constants.SP_IS_REMEMBER, checked);
        });

        binding.tvUserAgreement.setOnClickListener(view -> {
            // TODO 用户协议
            mSwipeBackHelper.forward(UserAgreementActivity.class);
        });

        binding.tvPrivacy.setOnClickListener(view -> {
            // TODO 隐私政策
            mSwipeBackHelper.forward(PrivacyActivity.class);
        });

        setRemember();

        SPUtils.getInstance().put(Constants.SP_USER_FROM_LOGIN, true);

        String deviceId = SPUtils.getInstance().getString(Constants.SP_DEVICE_ID, "");
        if("".equals(deviceId)) {
            if (ContextCompat.checkSelfPermission(com.nopay.cdxphone.ui.ativity.LoginActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(com.nopay.cdxphone.ui.ativity.LoginActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
            } else {
                SPUtils.getInstance().put(Constants.SP_DEVICE_ID, DeviceIdManager.getId(com.nopay.cdxphone.ui.ativity.LoginActivity.this));
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SPUtils.getInstance().put(Constants.SP_DEVICE_ID, DeviceIdManager.getId(com.nopay.cdxphone.ui.ativity.LoginActivity.this));
    }

    private void getPermissionToLogin() {
        doLogin();
    }

    private void setRemember() {
        if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Constants.SP_REMEMBER))) {
            binding.cbVerificationCodeLogin.setChecked(true);
            String[] split = RememberUitls.getRemember();
            int length = split.length;
            if (length == 2) {
                binding.loginEtUser.setText(split[0]);
                binding.loginEtPassword.setText(split[1]);
                binding.loginEtUser.postInvalidate();
                CharSequence text = binding.loginEtUser.getText();
                if (!TextUtils.isEmpty(text)) {
                    Selection.setSelection((Spannable) text, text.length());
                }
            }
        } else {
            binding.loginEtUser.setText("");
            binding.loginEtPassword.setText("");
        }
    }

    private void doLogin() {
        String userPhone = binding.loginEtUser.getText().toString().trim();
        String passWord = binding.loginEtPassword.getText().toString().trim();

        //配置请求对象开始
        LoginRequest loginRequestBean = new LoginRequest();
        loginRequestBean.setPhone(userPhone);
        loginRequestBean.setPassword(passWord);
        loginRequestBean.setEquipmentId(SPUtils.getInstance().getString(Constants.SP_DEVICE_ID, ""));

        //配置请求对象结束
        RequestBody body = getRequestBody(loginRequestBean);
        api.doLogin(body).enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        SPUtils.getInstance().put(Constants.SP_ACCOUNT, userPhone);
                        SPUtils.getInstance().put(Constants.SP_PASSWORD, passWord);
                        RememberUitls.setRemember(userPhone, passWord);
                        long userId = response.body().getData().getId();
                        String userName = response.body().getData().getUserName();
                        String phone = response.body().getData().getPhone();
                        String headUrl = response.body().getData().getHeadUrl();
                        String companyName = response.body().getData().getCompanyName();
                        int status = response.body().getData().getStatus();
                        String memberLevel = response.body().getData().getMemberLevel();
                        String invalidTime = response.body().getData().getInvalidTime();
                        String createTime = response.body().getData().getCreateTime();
                        SPUtils.getInstance().put(Constants.SP_USER_ID, userId);
                        SPUtils.getInstance().put(Constants.SP_USER_NAME, userName);
                        SPUtils.getInstance().put(Constants.SP_PHONE, phone);
                        SPUtils.getInstance().put(Constants.SP_HEAD_URL, headUrl);
                        SPUtils.getInstance().put(Constants.SP_COMPANY_NAME, companyName);
                        SPUtils.getInstance().put(Constants.SP_VIP_STATUS, status);
                        SPUtils.getInstance().put(Constants.SP_VIP_LEVEL, memberLevel);
                        SPUtils.getInstance().put(Constants.SP_VIP_INVALID_TIME, invalidTime);
                        SPUtils.getInstance().put(Constants.SP_ACCOUNT_CREATE_TIME, createTime);
                        mSwipeBackHelper.backwardAndFinish(MainActivity.class);
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                ToastUtils.showShort(com.nopay.cdxphone.ui.ativity.LoginActivity.this.getResources().getString(R.string.call_api_error));
            }
        });

    }

    private boolean checkInput() {
        String userPhone = binding.loginEtUser.getText().toString().trim();
        String passWord = binding.loginEtPassword.getText().toString().trim();
        if (TextUtils.isEmpty(userPhone)) {
            ToastUtils.showShort(getResources().getString(R.string.please_input_phone_number));
            return false;
        }
        if (TextUtils.isEmpty(passWord)) {
            ToastUtils.showShort(getResources().getString(R.string.please_input_phone_pwd));
            return false;
        }
        if (!RegexUtils.isMobileExact(userPhone)) {
            ToastUtils.showShort(getResources().getString(R.string.please_input_right_phone_number));
            return false;
        }

//        if(!binding.cbAgree.isChecked()) {
//            ToastUtils.showShort("请选择同意用户协议和隐私政策");
//            return false;
//        }
        return true;
    }

}
